package com.sourcetrip.arraylist;


import com.sourcetrip.raw.model.Student;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author: ZhouBert
 * @date: 2020/11/16
 * @description:
 * 需求：
 * 已知4个学生对象，要求将4个学生对象序列化到当前模块根目录下的stu.txt 中，
 * 序列化成功后，通过反序列化将文件中的数据读取出来，打印到控制台
 * 分析：
 * 如果不用集合就进行序列化，会造成反序列化时没法直接拿到方便的对象。
 */
public class SerTest02 {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		Student student1 = new Student("不知妻美刘强东", 11);
		Student student2 = new Student("悔创阿里杰克马",12);
		Student student3 = new Student("一无所有王健林",13);
		Student student4 = new Student("普通家庭马化腾",14);

		Path path = Paths.get(System.getProperty("user.dir"), "stu.txt");
		System.out.println("path = " + path);
		//String path = System.getProperty("user.dir") + "stu.txt";
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path.toString()));
		//放到数组里
		Student[] arr = new Student[4];
		arr[0]=student1;
		arr[1]=student2;
		arr[2]=student3;
		arr[3]=student4;
		oos.writeObject(arr);
		oos.close();

		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path.toString()));
		Student[] objectArr = (Student[])ois.readObject();
		for (Student student : objectArr) {
			System.out.println("student = " + student);
		}

	}
}
